function loadTeacherData() {
    $.ajax({
        url: "http://localhost:8080/teacher/list",
        method: "GET",
        dataType: "json",
        contentType: "application/json",
        cache: false,
        success: function (response) {
            $("#teachers-tbody").empty();

            $.each(response.data, function (index, teacher) {
                let teacherRowHTML = `<tr>
                    <td>${teacher.id}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.sex}</td>
                    <td>${teacher.age}</td>
                    <td>${teacher.major}</td>
                    <td>${teacher.address}</td>
                    <td>
                    <button class="btn btn-sm btn-primary" data-teacher-id="${teacher.id}">编辑</button>
                    <button class="btn btn-sm btn-danger" data-teacher-id="${teacher.id}">删除</button>
                    </td>
                    </tr>`;

                $("#teachers-tbody").append(teacherRowHTML);
            });
        },
        error: function (error) {
            console.error("获取教师数据失败：", error);
        }
    });
}

function initializeTeacherTable() {
    loadTeacherData();

    function resetForm() {
        $("#teacher-name").val("");
        $("#teacher-gender").val("");
        $("#teacher-age").val("");
        $("#teacher-major").val("");
        $("#teacher-address").val("");
    }

    $("#add-teacher-btn").click(function () {
        console.log("添加教师按钮被点击");

        var teacher_name = $("#teacher-name").val();
        var teacher_gender = $("#teacher-gender").val();
        var teacher_age = $("#teacher-age").val();
        var teacher_major = $("#teacher-major").val();
        var teacher_address = $("#teacher-address").val();

        if (teacher_name === "" || teacher_gender === "" || teacher_age === "" ||
            teacher_major === "" || teacher_address === "") {
            alert("输入不能为空！");
            return;
        }

        $.ajax({
            url: "http://localhost:8080/teacher/add",
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            data: JSON.stringify({
                "name": teacher_name,
                "sex": teacher_gender,
                "age": teacher_age,
                "major": teacher_major,
                "address": teacher_address
            }),
            success: function (response) {
                if (response.message == "ok") {
                    alert("添加成功！");
                    resetForm();
                    loadTeacherData();
                } else {
                    alert(response.message);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("添加教师处理过程中发生问题！");
            }
        });
    });

    $("#teachers-tbody").on("click", ".btn-danger", function () {
        console.log("删除教师按钮被点击");
        let teacherId = $(this).data("teacher-id");

        if (!confirm("确定要删除此教师吗？")) {
            return;
        }

        $.ajax({
            url: `http://localhost:8080/teacher/delete/${teacherId}`,
            method: "DELETE",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (response) {
                if (response.message == "ok") {
                    alert("教师已删除！");
                    loadTeacherData();
                } else {
                    alert("删除失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("删除教师失败：", error);
            }
        });
    });

    // 编辑教师
    $("#teachers-tbody").on("click", ".btn-primary", function () {
        let teacherRow = $(this).parent().parent();
        let teacherId = $(this).data("teacher-id");
        let teacherName = teacherRow.children().eq(1).text();
        let teacherGender = teacherRow.children().eq(2).text();
        let teacherAge = teacherRow.children().eq(3).text();
        let teacherMajor = teacherRow.children().eq(4).text();
        let teacherAddress = teacherRow.children().eq(5).text();

        $('#edit-teacher-id').val(teacherId);
        $('#edit-teacher-name').val(teacherName);
        $('#edit-teacher-gender').val(teacherGender);
        $('#edit-teacher-age').val(teacherAge);
        $('#edit-teacher-major').val(teacherMajor);
        $('#edit-teacher-address').val(teacherAddress);

        $('#editTeacherModal').modal('show');
    });

    $('#saveTeacherChangesBtn').click(function () {
        let teacherId = $('#edit-teacher-id').val();
        let teacherName = $('#edit-teacher-name').val();
        let teacherGender = $('#edit-teacher-gender').val();
        let teacherAge = $('#edit-teacher-age').val();
        let teacherMajor = $('#edit-teacher-major').val();
        let teacherAddress = $('#edit-teacher-address').val();

        updateTeacherData(teacherId, teacherName, teacherGender, teacherAge, teacherMajor, teacherAddress);
        $('#editTeacherModal').modal('hide');
    });

    function updateTeacherData(teacherId, teacherName, teacherGender, teacherAge, teacherMajor, teacherAddress) {

        $.ajax({
            url: `http://localhost:8080/teacher/edit/${teacherId}`,
            method: "PUT",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "name": teacherName,
                "sex": teacherGender,
                "age": teacherAge,
                "major": teacherMajor,
                "address": teacherAddress
            }),
            cache: false,
            success: function (response) {
                if (response.message == "ok") {
                    alert("更新成功！");
                    loadTeacherData();
                } else {
                    alert("更新失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("更新教师数据失败：", error);
            }
        });
    }
}
function bindTeacherTableEvents(){
    initializeTeacherTable();
}